<?php

namespace app\manage\controller;

use \core\libs\db;
use \core\libs\input;

class base extends \core\libs\controller {
	// 控制器 
    public $baseClass; 
	// 方法 
    public $baseAction; 
    // 存储处理后的参数 
    protected $input = [];
	// 图片路径
	protected $server_image = "/static/";
    // 初始化
    public function __initialize() {
		// 控制器
		$this->baseClass = $GLOBALS["controller"];
		// 方法
		$this->baseAction = $GLOBALS["action"];
        //验证登陆 
        $this->check_session('admin__name');
		// 判断是否多语言 
		if(input::session("admin__language")) {
			db::$table_prefix = input::session("admin__language") . "_";
		}
    }

	// 获取多图片上传组件
	protected function get_upload_multiple($id, $inputname, $picArray) {
		if($picArray) {
			foreach(explode(',', $picArray) as $key => $v) {
				if($v) {     
					$piclist .= '<li>
									<a onClick="app.uploadFile().multiple_remove(this)">移除×</a>
									<div><img src = "'. $this->server_image . trim($v) .'" /></div>
								 </li>';
				}
			}
		}
		else {
			$piclist = "<span>还没有上传图片。</span>";
		}
		

		$html = '<div class="zss-pic-items">      
					<iframe src="/plugins/upload/multiple?name='. $id .'" width="100%" height="45" scrolling="no" frameborder="0"></iframe>
					<div class="zss-pic-multiple">                          
						<ul id="s_'. $id .'">                                    
							'. $piclist .'
						</ul>
						
						<button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="app.uploadFile().multiple_remove_all(\''. $id .'\')"><i class="layui-icon">&#xe640;</i> 删除所有图片</button>
						<input type="hidden" name="'. $inputname .'" id="'. $id .'" value="'. $picArray .'">
					</div> 
				</div>
				<script type="text/javascript">
					//移动图片
					$("#s_'. $id .'").dragsort({
						dragSelector: "div", 
						placeHolderTemplate: "<li class=\'placeHolder\'><div></div></li>", 
						dragEnd: function() {
							app.uploadFile().get_multiple(\''. $id .'\');
						}
					});
				</script>';

		
		echo $html;
	}

	// 获取单图片上传组件
	protected function get_upload_image($id, $inputname, $picArray, $num = 1) {
		$piclist = "";
		if($picArray) {
			foreach(explode(',', $picArray) as $key => $v) {
				$img = "";
				if($v) {     
					$img = '<img src = "'.$this->server_image.$v.'" />';
				}
				$piclist .= '<div class="zss-pic-items">                                 
								<div class="zss-picbox" id="s_'. $id .'_'. ($key+1) .'">
									'. $img .'
								</div>
												
								<input type="hidden" name="'. $inputname .'[]" id="'. $id .'_'. ($key+1) .'" value="'. $v .'">
								<iframe src="/plugins/upload/image?name='. $id .'_'. ($key+1) .'"" width="100%" height="45" scrolling="no" frameborder="0"></iframe>  
								<button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="app.uploadFile().remove_file(this)"><i class="layui-icon">&#xe640;</i> 移除</button>
							</div>';
				
			}
		}

		echo '<div id="container_'. $id .'">
					'. $piclist .'
			  </div>
					
			  <button type="button" class="layui-btn" data-max="'. $num.'" data-input_name="'. $inputname .'" data-container="#container_'. $id .'" data-filename="image" onclick="app.uploadFile().add_file(this)">
					<i class="layui-icon">&#xe608;</i> 增加一张图片
			  </button>
			  <div class="layui-inline layui-word-aux" id="tips">图片大小2MB，类型jpg, png, gif, bmp</div>';
	}

	// 获取单视频上传组件
	protected function get_upload_video($id, $inputname, $picArray, $num = 1) {
		$piclist = "";
		if($picArray) {
			foreach(explode(',', $picArray) as $key => $v) {
				$img = "";
				if($v) {     
					$img = '<video src="'.$this->server_image.$v.'" height="80" width="80" controls="controls"></video>';
				}
				$piclist .= '<div class="zss-pic-items">                                 
								<div class="zss-picbox" id="s_'. $id .'_'. ($key+1) .'">
									'. $img .'
								</div>
												
								<input type="hidden" name="'. $inputname .'[]" id="'. $id .'_'. ($key+1) .'" value="'. $v .'">
								<iframe src="/plugins/upload/video?name='. $id .'_'. ($key+1) .'"" width="100%" height="45" scrolling="no" frameborder="0"></iframe>  
								<button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="app.uploadFile().remove_file(this)"><i class="layui-icon">&#xe640;</i> 移除</button>
							</div>';
				
			}
		}

		echo '<div id="container_'. $id .'">
					'. $piclist .'
			  </div>
					
			  <button type="button" class="layui-btn" data-max="'. $num.'" data-input_name="'. $inputname .'" data-container="#container_'. $id .'" data-filename="video" onclick="app.uploadFile().add_file(this)">
					<i class="layui-icon">&#xe608;</i> 增加一个视频
			  </button>
			  <div class="layui-inline layui-word-aux" id="tips">文件大小10MB，类型mp4</div>';
	}

	// 获取单文件上传组件
	protected function get_upload_file($id, $inputname, $picArray, $num = 1) {
		$piclist = "";
		if($picArray) {
			foreach(explode(',', $picArray) as $key => $v) {
				$img = "";
				if($v) {     
					$img = '附件地址：<a href="'.$this->server_image.$v.'" target="_blank">'. $v .'</a>';
				}
				$piclist .= '<div class="zss-pic-items">                                 
								<div class="zss-picbox" id="s_'. $id .'_'. ($key+1) .'">
									'. $img .'
								</div>
												
								<input type="hidden" name="'. $inputname .'[]" id="'. $id .'_'. ($key+1) .'" value="'. $v .'">
								<iframe src="/plugins/upload/file?name='. $id .'_'. ($key+1) .'"" width="100%" height="45" scrolling="no" frameborder="0"></iframe>  
								<button type="button" class="layui-btn layui-btn-primary layui-btn-sm" onclick="app.uploadFile().remove_file(this)"><i class="layui-icon">&#xe640;</i> 移除</button>
							</div>';
				
			}
		}

		echo '<div id="container_'. $id .'">
					'. $piclist .'
			  </div>
					
			  <button type="button" class="layui-btn" data-max="'. $num.'" data-input_name="'. $inputname .'" data-container="#container_'. $id .'" data-filename="file" onclick="app.uploadFile().add_file(this)">
					<i class="layui-icon">&#xe608;</i> 增加一个文件
			  </button>
			  <div class="layui-inline layui-word-aux" id="tips">文件大小10MB，类型pdf</div>';
	}

	// 获取当前位置
	protected function get_loc($url, $tag = "") {
		$nav = $this->get_menu();

		if($tag) {
			$tag = " <a><cite>{$tag}</cite></a>";
		}
		foreach($nav as $val) {
			if($val["url"] == $url) return "<a>{$val['name']}</a>{$tag} ";
			foreach($val["child"] as $val_2) {
				if($val_2["url"] == $url) return "<a>{$val['name']}</a> <a>{$val_2['name']}</a>{$tag} ";
				foreach($val_2["child"] as $val_3) {
					if($val_3["url"] == $url) return "<a>{$val['name']}</a> <a>{$val_2['name']}</a> <a>{$val_3['name']}</a>{$tag} ";
				}
			}
		}
	}

	// 获取后台菜单
	protected function get_menu() {
		$content_menu = [];
		$result = db::fetchAll("category", "category_cid in (1,2,36) and category_add = 1 order by category_id");
		foreach($result as $val) {
			$content_menu[] = ["name" => $val["category_name"], "url" => "content?mid=" . $val["category_id"], "power" => "list,edit", "child" => []];
		}

		return array(
			["name" => "控制台", "url" => "console", "icon" => "layui-icon-console", "power" => "", "child" => []],
			["name" => "小福豹H5", "url" => "", "icon" => "layui-icon-app", "power" => "", "child" => [
				["name" => "用户管理", "url" => "user", "power" => "list,edit", "child" => []],
				["name" => "视频管理", "url" => "works", "power" => "list,edit", "child" => []]
			]],
			// ["name" => "分类管理", "url" => "category", "icon" => "layui-icon-template-1", "power" => "list,edit", "child" => []],
			// ["name" => "内容管理", "url" => "", "icon" => "layui-icon-app", "power" => "", "child" => $content_menu],
			// ["name" => "报名管理", "url" => "apply", "icon" => "layui-icon-survey", "power" => "list,edit", "child" => []],
			// ["name" => "广告管理", "url" => "", "icon" => "layui-icon-picture", "power" => "", "child" => [
			// 	["name" => "广告", "url" => "ads", "power" => "list,edit", "child" => []],
			// 	["name" => "广告位置", "url" => "ads_position", "power" => "list,edit", "child" => []],
			// ]],
			// ["name" => "网站设置", "url" => "", "icon" => "layui-icon-set", "power" => "", "child" => [
			// 	["name" => "基础配置", "url" => "basic", "power" => "list,edit", "child" => []],
			// ]],
			["name" => "系统管理员", "url" => "", "icon" => "layui-icon-friends", "power" => "", "child" => [
				["name" => "管理员列表", "url" => "admin", "power" => "list,edit", "child" => []],
				["name" => "管理组", "url" => "group", "power" => "list,edit", "child" => []],
			]],
		);
	}

	// 管理组权限菜单
	protected function group_list($menu, $id) {
		if($menu["power"]) {
			$power_array = [
				"list" => "查看",
				"edit" => "编辑"
			];
			
			$power = explode(",", $menu["power"]);
			foreach($power as $v) {
				$checked = "";
				if($this->is_check($menu["url"] . "_" . $v, $id)) {
					$checked = "checked";
				}

				echo '<input type="checkbox" name="group_power[]" value="'. $menu["url"] . "_" . $v .'" title="'. $menu["name"] . "-" . $power_array[$v] .'" '. $checked .'>';
			}
		}

		if($menu["child"]) {
			foreach($menu["child"] as $val) {
				$this->group_list($val, $id);
			}
		}
	}

    /*
     * 检查权限
     */
    protected function is_level($name, $url = '/manage/console') {
		$id = input::session("admin__id");
		$admin = db::fetch("admin", "id='$id'", "admin_group");

        if(!$this->is_check($name, $admin["admin_group"])) {		
            alert('错误：你没有此栏目管理权限!', $url); 
            exit;
        }
    }

	// 验证权限
	protected function is_check($name, $id = 0) {
		$row = db::fetch('group', "group_id='$id'", "group_power");
		if($row) {			
			return in_array($name, explode(",", $row['group_power']));
		}	
		return false;
	}


    /*	
     * session是否有值
     * $name 名称	 
     */	
    protected function check_session($name){
        $is = input::session($name);
        if(!$is) {
            echo "<script>window.parent.location.href='/manage/login', '_blank';</script>";
        }
    }

	// 获取页面地址栏参数
	protected function get_base_args($args = "", $type = 0) {
		// 去掉分页参数
        if($type == 1) {
            return $args;
        }
        return "{$args}&page={$_GET['page']}";
	}

    /*	
	 * 内容分类		 
	 * @param $table_name 表名,  $where 条件, $cid 选中ID, $icon 前缀
	 */	
	protected function category($table_name, $where, $cid, $icon = '') {
		$result = db::fetchAll(
			$table_name, 
			$where
		);
		
		foreach($result as $row) {
			echo "<option value=".$row['category_id'];
			
			if($row[0] == $cid)	{
				echo " selected";
			}
			
			echo ">".$icon.$row['category_name']."</option>";	
		}
    }


    /*	
	 * 递归全部分类 下拉框	 
	 * @param $id 开始循环ID, $cid 选中ID	
	 */
	protected function recursive_category_select_new($id, $cid, $where = "", $n = 0) { 

		$result = db::fetchAll(
			"category", 
			"category_id = '$id' $where order by category_order desc, category_id", 
			"category_id, category_cid, category_name"
		);

		$n ++;
		foreach($result as $row) {
			$html = '';
			$html .= '<option value="'.$row['category_id'].'"';
			
			if(is_array($cid)) {
				if(in_array($row['category_id'], $cid))	$html .= 'selected';
			}
			else {
				if($row['category_id'] == $cid)	$html .= 'selected';
			}
				
			$html .= '>';
			
			for($i = 1; $i < $n; $i++) {
				$html .= '&nbsp;&nbsp;';
			}
			
			if($n > 1) $html .= '├';
			
			$html .= $row['category_name'].'</option>';
			echo $n;
			echo $html;			
			$this->recursive_category_select($row['category_id'], $cid, $where, $n);
		}
	}

	/*	
	 * 递归全部分类 下拉框	 
	 * @param $id 开始循环ID, $cid 选中ID	
	 */
	protected function recursive_category_select($id, $cid, $where = "", $n = 0) { 
		$result = db::fetchAll(
			"category", 
			"category_cid = '$id' $where order by category_order desc, category_id", 
			"category_id, category_cid, category_name"
		);
		
		$n ++;
		foreach($result as $row) {
			$html = '';
			$html .= '<option value="'.$row['category_id'].'"';
			
			if(is_array($cid)) {
				if(in_array($row['category_id'], $cid))	$html .= 'selected';
			}
			else {
				if($row['category_id'] == $cid)	$html .= 'selected';
			}
				
			$html .= '>';
			
			for($i = 1; $i < $n; $i++) {
				$html .= '&nbsp;&nbsp;';
			}
			
			if($n > 1) $html .= '├';
			
			$html .= $row['category_name'].'</option>';
			echo $n;
			echo $html;			
			$this->recursive_category_select($row['category_id'], $cid, $where, $n);
		}
	}
	
	
	/*	
	 * 递归分类		 
	 * @param $id 开始循环ID， $n左边间距
	 */	
	protected function recursive_menu($id = 0, $type = 0) {

		$result = db::fetchAll(
			"category", 
			"category_cid = '$id' order by category_order desc, category_id", 
			"category_id, category_cid, category_name, category_order, category_state, category_content"
		);	
		
		$html = '';
        $html_start = '';
		foreach($result as $row) {

			$btn = '';
			//添加
			$btn .= '<a class="layui-icon layui-icon-add-1" data-type="add" href="'. U('category?cid=' . $row['category_id']) .'"></a>';
			//修改	
			$btn .= '<a class="layui-icon layui-icon-edit" data-type="update" href="'. U('category?cid=' . $row['category_cid'] . '&id=' . $row['category_id']) . '"></a>';
			//删除
			$btn .= '<a class="layui-icon layui-icon-delete" data-type="del" href="'. U('category/delete?id=' . $row['category_id']) . '" onclick=\'if(confirm("您确定删除吗?此操作将不能恢复!")){ return true; } return false;\'></a>';
			

			// 标签
			$label = '';
            if($row['category_state']==0) $label .= ' <span class="layui-badge">隐藏</span>'; 

            $html_start .= '<div data-id="1" class="layui-tree-set layui-tree-setHide layui-tree-spread">
                                <div class="layui-tree-entry">
                                <div class="layui-tree-main">
                                    <span class="layui-tree-iconClick"><i class="layui-icon layui-icon-file"></i></span>
                                    <span class="layui-tree-txt">
                                        ['.$row['category_order'].'] 
                                        <a href="?cid='.$row['category_cid'].'&id='.$row['category_id'].'">'.$row['category_name'].'</a>
                                        '. $label .'
                                    </span>
                                    <div class="layui-btn-group layui-tree-btnGroup">'. $btn .'</div>
                                </div>
                                </div>
                                ' .$this->recursive_menu($row['category_id'], 1) . '
                            </div>';

			$html .= '<div class="layui-tree-pack layui-tree-lineExtend layui-tree-showLine" style="display: block;">
            			<div data-id="1000" class="layui-tree-set layui-tree-spread">
            			  <div class="layui-tree-entry">
            				<div class="layui-tree-main">
            					<span class="layui-tree-iconClick"><i class="layui-icon layui-icon-file"></i></span>
								<span class="layui-tree-txt">
									['.$row['category_order'].'] 
									<a href="?cid='.$row['category_cid'].'&id='.$row['category_id'].'">'.$row['category_name'].'</a>
									'. $label .'
								</span>
								<div class="layui-btn-group layui-tree-btnGroup">'. $btn .'</div>
            				</div>
						  </div>
						  ' .$this->recursive_menu($row['category_id'], 1) . '
            			</div>
					  </div>';
		}

		return $type ? $html : $html_start;
	}
	
	
	/*	
	 * 递归全部分类 下拉框	 
	 * @param $id 开始循环ID, $cid 选中ID	
	 */	
	protected function recursive_menu_select($id, $cid, $n = 0)	{

		$result = db::fetchAll(
			"category", 
			"category_cid = '$id'", 
			"category_id, category_cid, category_name"
		);
		
		$n ++;
		foreach($result as $row) {
			$html = '';
			$html .= '<option value="'.$row['category_id'].'"';
				
			if($row['category_id'] == $cid)
			{
				$html .= 'selected';
            }
				
			$html .= '>';
			
			for($i = 0; $i < $n; $i++)
			{
				$html .= '&nbsp;';
			}
			
			if($n > 0) $html .= '├';
			
			$html .= $row['category_name'].'</option>';
			
			echo $html;			
			$this->recursive_menu_select($row['category_id'], $cid, $n);
		}
	}
	

	//获取所有子类/孙类...的ID
	protected function get_cid_all($id, $array = []) {
		$array[] = $id;		
		$result_array = db::fetchAll(
			"category", 
			"category_cid = '$id'"
		);

		foreach($result_array as $row) {	
			$array = $this->get_cid_all($row['category_id'], $array);
		}

		return $array;
	}
	protected function get_category_ids($id, $array = []) {	
		return implode(',', $this->get_cid_all($id));
	}
}